<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\BaseController;
use App\Http\Requests\Api\UserRequest;
use App\Models\User;
use App\Transformers\UserTransformer;
use Illuminate\Http\Request;

class UserController extends BaseController
{
    /**
     * 用户列表
     */
    public function index(Request $request)
    {
        $username = $request->input('username');
        $status = $request->input('status');
//        搜索
        $users = User::when($username,function ($query) use ($username){
            $query->where('username', 'like', "%$username%");
        })
            ->when($status,function ($query) use ($status){
                $query->where('status', $status);
            })
            ->paginate( 20);  // 分页
//        响应生成器
        return $this->response->paginator($users,new UserTransformer());
    }
    /**
     * 添加用户
     */
    public function store(UserRequest $request)
    {
//        批量赋值
        $user = User::create([
            'username' => $request->input('username'),
            'password' => bcrypt($request->input('password'))
        ]);

        $user->assignRole($request->input('roles'));

        return $this->response->created();
    }

    /**
     * 更新用户
     */
    public function update(Request $request, User $user)
    {
        $request->validate([
            'username' => 'required|max:16',
            'roles' => 'required|array'
        ],[
            'username.required' => '用户名不能为空',
            'username.max' => '用户名不能超过16个字符',
            'roles.required' => '角色不能为空',
            'roles.array' => '角色必须是一个数组',
        ]);
//        批量赋值
        $user->update([
            'username' => $request->input('username')
        ]);

        $user->assignRole($request->input('roles'));
        return $this->response->noContent();
    }

    /**
     * 删除用户
     */
    public function destroy(User $user)
    {
        $user->delete();
        return $this->response->noContent();
    }

    /**
     * 用户状态
     */
    public function status(User $user)
    {
        $user->status = $user->status == 0 ? 1 : 0;
        $user->save();
        return $this->response->noContent();
    }
}
